package com.bird.generate.ddd.domain

import com.bird.component.ddd.model.entity.AggregateRoot
import com.bird.component.ddd.model.entity.BaseEntity
import com.bird.generate.ddd.domain.vo.Field
import kotlin.collections.plus

/**
 * 聚合根实体
 */
class AggregateRootEntity(
    //聚合根名称
    var name: String,
    //聚合根描述
    var description: String? = null,
    //聚合根英文名称(驼峰)
    var enName: String,
    //项目版本号
    var version: String,
    //所属module
    var moduleName: String,
    //所属项目
    var projectName: String,
    //包含值对象
    var valueObjects: List<ValueObjectEntity> = emptyList(),
    //包含实体
    var entities: List<EntityEntity> = emptyList(),
    //创建人
    var creator: String,
    //支持多租户
    var multiTenant: Boolean,
    /**
     * 项目包前缀
     */
    var comPrefix: String = "com.zz",
    //字段
    var fields: List<Field> = emptyList(),
    ) : BaseEntity(id = null), AggregateRoot {


    fun oneFieldValueObjectDeal() {
        //处理聚合和实体的属性，如果值对象中没有定义，并且实体的属性类型没有定义或者是enum的，主动添加单值对象
        var fields = this.fields
        var valueObjects = this.valueObjects
        var voEnNames = valueObjects.map { it.enName }
        fields.forEach {
            if (it.type.isNullOrEmpty() || it.type == "enum") {
                if (!voEnNames.contains(it.enName)) {
                    valueObjects =
                        valueObjects + ValueObjectEntity(
                            enName = it.enName,
                            name = it.name,
                            isEnum = it.type == "enum"
                        )
                }
                it.type = null
            }
        }
        this.entities.forEach { t ->
            voEnNames = valueObjects.map { it.enName }
            t.fields.forEach {
                if (it.type.isNullOrEmpty() || it.type == "enum") {
                    if (!voEnNames.contains(it.enName)) {
                        valueObjects =
                            valueObjects + ValueObjectEntity(
                                enName = it.enName,
                                name = it.name,
                                isEnum = it.type == "enum"
                            )
                    }
                    it.type = null
                }
            }
        }
        this.valueObjects = valueObjects
    }

    fun emptyFieldsDeal() {
        //处理实体的属性，如果没有定义属性，主动添加一个id属性
        this.entities.forEach {
            it.fields = it.fields.filter{f-> f.enName.isNotBlank()}
        }
        this.valueObjects.forEach {
            it.fields = it.fields.filter{f-> f.enName.isNotBlank()}
        }
        this.fields = this.fields.filter{f-> f.enName.isNotBlank() }
    }


}